﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebMvc.Controllers;
using Common;
using Models;
using System.Web;
using WebMvc.Areas.Models;
using System.Linq.Expressions;
using Common.Attributes;
using System.Threading.Tasks;
using System.Collections;
using System.IO;
using log4net;
using WebMvc.Models;

namespace WebMvc.APIControllers
{
    public class TijianController : BaseApiController
    {
        ILog logWriter = LogManager.GetLogger("TijianController");

        #region 体检套餐查询接口
        /// <summary>
        /// 体检套餐查询接口
        /// </summary>
        /// <param name="username">接口账号</param>
        /// <param name="password">接口密码</param>
        /// <param name="state">状态。0：查询，1：核销</param>
        /// <param name="cardId">卡号</param>
        /// <param name="cardPwd">密码</param>
        /// <returns></returns>

        public JsonData GetPackage(string username, string password, string cardId, string cardPwd, int state = 0, string pCode="")
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(cardId) || string.IsNullOrEmpty(cardPwd))
            {
                return new JsonData() { returnCode = "400", message = "输入参数异常", data = null };
            }
            if (!username.Trim().Equals("jhjtmall") && !password.Trim().Equals("jhjt@mall"))
            {
                return new JsonData() { returnCode = "401", message = "无效的用户密码校验", data = null };
            }
            try
            {
                BS_CodePool codepool = new BS_CodePool();
                string pwd = DESEncrypt.Encrypt(cardPwd.Trim());

                var codepoolvar = oc.BllSession.IBS_CodePoolBLL.Entities.Where(cp => cp.CPName.Contains(cardId.Trim()) && cp.CPPassword.Contains(pwd)).ToList();
                List<int> mpIds = new List<int>();

                if (codepoolvar != null&&codepoolvar.Count()>0)
                {
                    codepool = codepoolvar.FirstOrDefault();

                    if (!string.IsNullOrEmpty(codepool.CPMedicalPackageId))
                    {
                        mpIds = StrHelper.GetIntListByStr(codepool.CPMedicalPackageId);
                    }

                    List<BS_MedicalPackage> medicalPackageList = new List<BS_MedicalPackage>();
                    if (mpIds != null)
                    {
                        medicalPackageList = oc.BllSession.IBS_MedicalPackageBLL.Entities.Where(mp => mpIds.Contains(mp.MPId)).ToList();
                    }
                    if (state == 0)
                    {
                        if (medicalPackageList != null)
                        {
                            List<PackageModel> packageList = new List<PackageModel>();
                            foreach (BS_MedicalPackage model in medicalPackageList)
                            {
                                PackageModel package = new PackageModel();

                                package.CardId = codepool.CPName;
                                package.CardPwd = codepool.CPPassword;
                                package.CPStatus = codepool.CPStatus;
                                package.MPName = model.MPName;
                                package.MPCode = model.MPCode;
                                package.MPPrice = model.MPPrice;
                                package.MPSex = model.MPSex;
                                package.MPMarried = model.MPMarried;
                                package.MPDescription = model.MPDescription;

                                packageList.Add(package);
                            }

                            return new JsonData() { returnCode = "200", message = "ok", data = packageList };
                        }
                        return new JsonData() { returnCode = "402", message = "该卡号没有查询到对应的套餐", data = null };
                    }
                    else if (state == 1)
                    {
                        if (codepool.CPStatus == 3)
                        {
                            return new JsonData() { returnCode = "602", message = "该卡号已使用，不能重复使用！", data = null };
                        }
                        if (codepool.CPStatus == 4)
                        {
                            return new JsonData() { returnCode = "603", message = "该卡号已作废，不能进行核销！", data = null };
                        }

                        BS_MedicalPackage pa = new BS_MedicalPackage();
                        if (string.IsNullOrEmpty(pCode.Trim()))
                        {
                            var palist = oc.BllSession.IBS_MedicalPackageBLL.Entities.Where(cp => cp.MPCode.Equals(pCode.Trim())).ToList();
                            if (palist != null && palist.Count() > 0)
                            {
                                pa = palist.FirstOrDefault();
                            }
                        }
                        else
                        {
                            pa = null;
                        }

                        //核销
                        codepool.CPStatus = 3;

                        Expression<Func<BS_CodePool, object>>[] ignoreProperties = null;

                        if (pa != null)
                        {
                            codepool.CPPrice = pa.MPPrice;
                            codepool.CPBalance = pa.MPPrice;
                            ignoreProperties = new Expression<Func<BS_CodePool, object>>[]{
                                cp=>cp.CPId,cp=>cp.CPTId,cp=>cp.CPTName,cp=>cp.CPBranchId,cp=>cp.CPBranchName,cp=>cp.CPCreateTime
                            };
                        }
                        else
                        {
                            ignoreProperties = new Expression<Func<BS_CodePool, object>>[]{
                                cp=>cp.CPId,cp=>cp.CPTId,cp=>cp.CPTName,cp=>cp.CPBranchId,cp=>cp.CPBranchName,cp=>cp.CPCreateTime
                            };
                        }
                        
                        int iret = oc.BllSession.IBS_CodePoolBLL.Modify(codepool, ignoreProperties);
                        if (iret > 0)
                        {
                            return new JsonData() { returnCode = "200", message = "该卡号核销成功", data = null };
                        }
                        else
                        {
                            return new JsonData() { returnCode = "600", message = "该卡号核销失败", data = null };
                        }

                    }
                    else
                    {
                        return new JsonData() { returnCode = "405", message = "该卡号没有查询到套餐", data = null };
                    }
                }
                else
                {
                    return new JsonData() { returnCode = "403", message = "该卡号没有查询到套餐", data = null };
                }
            }
            catch (Exception ex)
            {
                logWriter.Error("GetPackage" + ex.Message);
                return new JsonData() { returnCode = "400", message = ex.Message, data = null };
            }
        }
        #endregion

        #region 体检套餐查询接口
        public JsonData GetAllPackage()
        {
            string pwd1 = DESEncrypt.Decrypt("61A7FB1082461B2D", System.Configuration.ConfigurationSettings.AppSettings["decryptkey"]);

            try
            {
                var codepoolList = oc.BllSession.IBS_MedicalPackageBLL.Entities.Select(cp => new
                    {
                        MPName = cp.MPName,
                        MPCode = cp.MPCode,
                        MPPrice = cp.MPPrice,
                        MPSex = cp.MPSex,
                        MPMarried = cp.MPMarried,
                        MPDescription = cp.MPDescription
                    }).ToList();

                if (codepoolList.Count > 0)
                {
                    return new JsonData() { returnCode = "200", message = "ok", data = codepoolList };
                }
                else
                {
                    return new JsonData() { returnCode = "400", message = "系统没有设置套餐信息", data = null };
                }
            }
            catch (Exception ex)
            {
                logWriter.Error("GetAllPackage" + ex.Message);
                return new JsonData() { returnCode = "400", message = ex.Message, data = null };
            }
        }
        #endregion

        #region 上传PDF文件
        /// <summary>
        /// 上传PDF文件
        /// </summary>
        /// <param name="username">接口访问用户名</param>
        /// <param name="password">接口访问密码</param>
        /// <param name="cardId">卡号</param>
        /// <returns></returns>
        public Task<Hashtable> PostFileUpload(string username, string password, string cardId)
        {
            try
            {
                // 检查是否是 multipart/form-data 
                if (!Request.Content.IsMimeMultipartContent("form-data"))
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                //文件保存目录路径 
                string SaveTempPath = "~/File/" + DateTime.Now.ToString("yyyyMM") + "/";
                String dirTempPath = HttpContext.Current.Server.MapPath(SaveTempPath);
                if (Directory.Exists(dirTempPath) == false)
                {
                    Directory.CreateDirectory(dirTempPath);
                }
                // 设置上传目录 
                var provider = new MultipartFormDataStreamProvider(dirTempPath);
                //var queryp = Request.GetQueryNameValuePairs();//获得查询字符串的键值集合 
                var task = Request.Content.ReadAsMultipartAsync(provider).
                    ContinueWith<Hashtable>(o =>
                    {
                        Hashtable hash = new Hashtable();

                        hash["returnCode"] = 400;
                        hash["message"] = "上传出错";
                        var file = provider.FileData[0];//provider.FormData 
                        string orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');
                        FileInfo fileinfo = new FileInfo(file.LocalFileName);
                        //最大文件大小 
                        int maxSize = 10000000;
                        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(cardId))
                        {
                            hash["returnCode"] = 400;
                            hash["message"] = "输入参数异常";
                        }
                        else if (!username.Trim().Equals("jhjtmall") || !password.Trim().Equals("jhjt@mall"))
                        {
                            hash["returnCode"] = 400;
                            hash["message"] = "无效的用户密码校验";
                        }
                        else if (fileinfo.Length <= 0)
                        {
                            hash["returnCode"] = 400;
                            hash["message"] = "请选择上传文件。";
                        }
                        else if (fileinfo.Length > maxSize)
                        {
                            hash["returnCode"] = 400;
                            hash["message"] = "上传文件大小超过限制。";
                        }
                        else
                        {
                            string fileExt = orfilename.Substring(orfilename.LastIndexOf('.'));
                            //定义允许上传的文件扩展名 
                            String fileTypes = "gif,jpg,jpeg,png,bmp,pdf";
                            if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
                            {
                                hash["returnCode"] = 400;
                                hash["message"] = "上传文件扩展名是不允许的扩展名。";
                            }
                            else
                            {
                                String newFileName = cardId;//DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                                fileinfo.CopyTo(Path.Combine(dirTempPath, newFileName + fileExt), true);
                                fileinfo.Delete();
                                string message = string.Empty;
                                if (Model_BS_Report.AddReportByCardId(cardId, "File/" + DateTime.Now.ToString("yyyyMM") + "/" + newFileName + fileExt,out message))
                                {
                                    hash["returnCode"] = 200;
                                    hash["message"] = "上传成功";
                                }
                                else
                                {
                                    hash["returnCode"] = 400;
                                    hash["message"] = message;
                                }
                            }
                        }
                        return hash;
                    });
                return task;
            }
            catch (Exception ex)
            {
                logWriter.Error("PostFileUpload" + ex.Message);
                throw ex;
            }
        }
        
        #endregion

        
    }
}
